import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../models/puzzle_piece.dart';
import '../models/puzzle_game.dart';
import '../../core/constants.dart';
import 'package:image/image.dart' as img;

/// 拼图生成服务
/// 
/// 开发思路分析：
/// 1. 算法核心 - 将完整图片分割成可拖拽的拼图块
/// 2. 性能优化 - 使用异步处理，避免UI阻塞
/// 3. 可扩展设计 - 支持不同形状、难度的拼图生成
/// 4. 状态管理 - 确保生成过程的状态可追踪
/// 
/// 
/// 
/// 这是整个拼图游戏的核心算法实现
/// 拼图生成服务
class PuzzleGeneratorService {
  // 单例模式
  static final PuzzleGeneratorService _instance = PuzzleGeneratorService._internal();
  factory PuzzleGeneratorService() => _instance;
  PuzzleGeneratorService._internal();
  
  // 生成状态跟踪
  final bool _isGenerating = false;
  String? _currentImagePath;
  int? _currentGridSize;
  
  /// 生成完整的拼图游戏
  Future<PuzzleGame> generatePuzzleGame({
    required String imagePath,
    required DifficultyLevel difficulty,
  }) async {
    debugPrint('🧩 [PuzzleGenerator] 开始生成 ${difficulty.displayName} 难度拼图');
    
    try {
      // 步骤 1: 加载原始尺寸图片并获取其宽高比
      final ui.Image sourceImage = await _loadImageFromAssets(imagePath);
      final double aspectRatio = sourceImage.width / sourceImage.height;
      debugPrint('🖼️ 图片加载成功, 原始尺寸: ${sourceImage.width}x${sourceImage.height}, 宽高比: $aspectRatio');

      // 步骤 2: 使用图片对象生成并打乱拼图块列表
      final pieces = await generatePieces(
        sourceImage: sourceImage,
        gridSize: difficulty.gridSize,
      );
      
      // 步骤 3: 创建游戏状态
      final game = PuzzleGame(
        pieces: pieces,
        status: GameStatus.initial,
        difficulty: difficulty,
        imagePath: imagePath,
        imageAspectRatio: aspectRatio,
      );
      
      debugPrint('✅ [PuzzleGenerator] 拼图生成完成，共 ${pieces.length} 个拼图块');
      return game;
      
    } catch (e) {
      debugPrint('❌ [PuzzleGenerator] 拼图生成失败: $e');
      rethrow;
    }
  }

  /// 从资源文件加载图片 (加载原始尺寸)
  Future<ui.Image> _loadImageFromAssets(String assetPath) async {
    try {
      final ByteData data = await rootBundle.load(assetPath);
      final Uint8List bytes = data.buffer.asUint8List();
      // 关键修复：移除 targetWidth/Height，加载原始尺寸图片，确保比例和切割的准确性
      final ui.Codec codec = await ui.instantiateImageCodec(bytes); 
      final ui.FrameInfo frame = await codec.getNextFrame();
      return frame.image;
    } catch (e) {
      debugPrint('❌ [PuzzleGenerator] 图片加载失败: $assetPath, 错误: $e');
      throw Exception('无法加载图片: $assetPath');
    }
  }

  /// 生成拼图块列表 (物理切割并打乱)
  Future<List<PuzzlePiece>> generatePieces({
    required ui.Image sourceImage,
    required int gridSize,
  }) async {
    // 1. 将 dart:ui 的 Image 转换为 image 包的 Image
    final ByteData? byteData = await sourceImage.toByteData(format: ui.ImageByteFormat.png);
    final Uint8List pngBytes = byteData!.buffer.asUint8List();
    final img.Image image = img.decodeImage(pngBytes)!;

    // 2. 计算每一块的精确像素尺寸
    final int pieceWidth = image.width ~/ gridSize;
    final int pieceHeight = image.height ~/ gridSize;

    final pieces = <PuzzlePiece>[];
    for (int i = 0; i < gridSize * gridSize; i++) {
      final int row = i ~/ gridSize;
      final int col = i % gridSize;

      final int x = col * pieceWidth;
      final int y = row * pieceHeight;

      // 3. 进行物理切割
      final img.Image pieceImage = img.copyCrop(
        image,
        x: x,
        y: y,
        width: pieceWidth,
        height: pieceHeight,
      );

      // 4. 转换回 dart:ui 的 Image
      final ui.Codec codec = await ui.instantiateImageCodec(img.encodePng(pieceImage));
      final ui.FrameInfo frameInfo = await codec.getNextFrame();
      final ui.Image finalPieceImage = frameInfo.image;

      // 5. 创建 PuzzlePiece 模型
      final piece = PuzzlePiece(
        id: i,
        correctRow: row,
        correctCol: col,
        image: finalPieceImage,
        currentRow: -1,
        currentCol: -1,
        position: Offset.zero,
        size: Size(pieceWidth.toDouble(), pieceHeight.toDouble()),
        clipPath: Path(),
      );
      pieces.add(piece);
    }
    
    // 6. 在返回之前，打乱列表！
    pieces.shuffle();
    debugPrint('✅ 物理切割完成，并已打乱顺序，生成 ${pieces.length} 个拼图块');

    return pieces;
  }
  
  /// 重新打乱现有拼图
  List<PuzzlePiece> reshufflePieces(List<PuzzlePiece> pieces) {
    if (pieces.isEmpty) return pieces;
    final shuffled = List<PuzzlePiece>.from(pieces);
    shuffled.shuffle();
    return shuffled;
  }
  
  /// 检查拼图完成度
  PuzzleGameValidationResult validatePuzzleCompletion(List<PuzzlePiece> pieces) {
    final totalPieces = pieces.length;
    final correctlyPlacedPieces = pieces.where((p) => p.isPlaced).length;
    
    return PuzzleGameValidationResult(
      isCompleted: correctlyPlacedPieces == totalPieces,
      completionPercentage: correctlyPlacedPieces / totalPieces,
      correctPieces: correctlyPlacedPieces,
      totalPieces: totalPieces,
      incorrectPieces: pieces.where((p) => !p.isPlaced && !p.isInCorrectPosition).toList(),
    );
  }
  
  /// 自动解决拼图（调试用）
  List<PuzzlePiece> autoSolvePuzzle(List<PuzzlePiece> pieces) {
    debugPrint('🤖 [PuzzleGenerator] 自动解决拼图（调试模式）');
    return pieces.map((piece) => piece.snapToCorrectPosition()).toList();
  }
  
  /// 获取提示（返回下一个应该放置的拼图块）
  PuzzlePiece? getNextHint(List<PuzzlePiece> pieces) {
    return pieces.where((piece) => !piece.isPlaced).firstOrNull;
  }
  
  /// 验证拼图块放置是否正确
  bool validatePiecePlacement(PuzzlePiece piece) {
    return piece.isNearCorrectPosition;
  }
  
  // =================== 状态查询方法 ===================
  bool get isGenerating => _isGenerating;
  String? get currentImagePath => _currentImagePath;
  int? get currentGridSize => _currentGridSize;
  
  Map<String, dynamic> getGenerationStats() {
    return {
      'isGenerating': _isGenerating,
      'currentImage': _currentImagePath,
      'currentGridSize': _currentGridSize,
      'supportedGridSizes': AppConstants.supportedGridSizes,
    };
  }
}



/// 拼图验证结果
class PuzzleGameValidationResult {
  final bool isCompleted;
  final double completionPercentage;
  final int correctPieces;
  final int totalPieces;
  final List<PuzzlePiece> incorrectPieces;
  
  const PuzzleGameValidationResult({
    required this.isCompleted,
    required this.completionPercentage,
    required this.correctPieces,
    required this.totalPieces,
    required this.incorrectPieces,
  });
  
  @override
  String toString() => 'PuzzleValidation('
      'completed: $isCompleted, '
      'progress: ${(completionPercentage * 100).toStringAsFixed(1)}%, '
      'correct: $correctPieces/$totalPieces)';
}

/// 拼图生成器工厂
class PuzzleGeneratorFactory {
  /// 创建标准拼图生成器
  static PuzzleGeneratorService createStandard() {
    return PuzzleGeneratorService();
  }
  
  /// 创建用于测试的拼图生成器
  static PuzzleGeneratorService createForTesting() {
    // 可以返回带有测试配置的生成器
    return PuzzleGeneratorService();
  }
}

/// 拼图生成器扩展方法
extension PuzzleGeneratorExtensions on PuzzleGeneratorService {
  /// 批量生成多个难度的拼图（V2.0功能预留）
  Future<Map<DifficultyLevel, PuzzleGame>> generateMultipleDifficulties(String imagePath) async {
    final results = <DifficultyLevel, PuzzleGame>{};
    
    for (final difficulty in DifficultyLevel.values) {
      try {
        final game = await generatePuzzleGame(
          imagePath: imagePath,
          difficulty: difficulty,
        );
        results[difficulty] = game;
      } catch (e) {
        debugPrint('⚠️ 生成 ${difficulty.displayName} 难度拼图失败: $e');
      }
    }
    
    return results;
  }
  
  /// 估算生成时间
  Duration estimateGenerationTime(int gridSize) {
    // 基于网格大小估算生成时间
    const baseTime = 500; // 毫秒
    final complexityFactor = gridSize * gridSize;
    return Duration(milliseconds: baseTime + complexityFactor * 10);
  }
}
